package cn.sccl.common.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 杨浩宇 on 2015-11-14.
 */
public class PerformaceInterceptor extends HandlerInterceptorAdapter {
    private Log logger = LogFactory.getLog(PerformaceInterceptor.class);
    private ThreadLocal<StopWatch> stopWatchThreadLocal = null;

    /**
     * This implementation always returns {@code true}.
     *
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StopWatch stopWatch = new StopWatch(handler.toString());
        if (stopWatchThreadLocal == null) {
            stopWatchThreadLocal = new ThreadLocal<StopWatch>();
        }
        stopWatchThreadLocal.set(stopWatch);
        stopWatch.start(handler.toString());
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
        return super.preHandle(request, response, handler);
    }

    /**
     * This implementation is empty.
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
        super.afterCompletion(request, response, handler, ex);
        String url = request.getRequestURL().toString();
        if (request.getQueryString() != null) {
            url += "?" + request.getQueryString();
        }
        StopWatch stopWatch = stopWatchThreadLocal.get();
        if(stopWatch != null){
            stopWatch.stop();
        }
        StringBuffer sb = new StringBuffer();
        sb.append("Rest性能监视：耗时(")
                .append(stopWatch!=null?stopWatch.getTotalTimeMillis():"")
                .append(") [")
                .append(request!=null?request.getMethod():"")
                .append("] | ")
                .append(url);
        logger.debug(sb);
    }


}
